/**
 * FileName: ProductTypeServiceImpl
 * Author: Wb
 * Date: 2025/9/24 10:33
 * Description:
 * History:
 */
package org.test.device.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.test.device.constant.AttributesValue;
import org.test.device.enty.ProductType;
import org.test.device.mapper.ProductTypeMapper;
import org.test.device.params.QueryProductTypeParam;
import org.test.device.params.SaveProductTypeParam;
import org.test.device.service.ProductTypeService;
import org.test.device.utils.SqlTypeConverter;
import org.test.device.architecture.exception.BusinessException;
import org.test.device.vo.product.ProductTypeVo;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 〈一句话功能简述〉<br>
 * 〈商品类型Service〉
 *
 * @author Wb
 * @create 2025/9/24
 * @since 1.0.0
 */
@Slf4j
@Service
@Transactional(readOnly = true)
public class ProductTypeServiceImpl implements ProductTypeService {

    @Autowired
    ProductTypeMapper productTypeMapper;

    /**
     * @Author Wb
     * @Description 获取所有的商品类型
     * @Date 14:44 2025/9/24
     * @Return List<ProductTypeVo>
     */
    @Override
    public List<Map<String,Object>> getProductTypeList() {
        List<Map<String,Object>> resultList=new ArrayList<>();
//        List<ProductTypeEnum> productTypeEnumList=ProductTypeEnum.getAllTypes(); // 废弃 枚举
        LambdaQueryWrapper<ProductType> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductType::getDeleted,0);
        List<ProductType> productTypeList=productTypeMapper.selectList(queryWrapper);
        productTypeList.forEach(enums->{
            Map<String,Object> productTypeMap=new HashMap<>();
            productTypeMap.put("id",enums.getId());
            productTypeMap.put("enName",enums.getEnName());
            productTypeMap.put("cnName",enums.getCnName());
            resultList.add(productTypeMap);
        });
        log.info("获取商品类型成功：{}", JSON.toJSONString(resultList));
        return resultList;
    }


    /**
     * @Author Wb
     * @Description 从数据库获取列表信息
     * @Date 9:28 2025/9/25
     * @Param []
     * @Return java.util.List<org.test.device.vo.product.ProductTypeVo>
     */
    @Override
    public List<ProductTypeVo> getProductTypeListBySQL(QueryProductTypeParam param) {
        LambdaQueryWrapper<ProductType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductType::getDeleted, 0);

        //判断为空查询全部
        Optional.ofNullable(param.getSearchKey())
                .map(String::trim)
                .filter(key -> !key.isEmpty())
                .ifPresent(key -> queryWrapper.and(wrapper -> wrapper
                        .like(ProductType::getEnName, key)
                        .or()
                        .like(ProductType::getCnName, key)
                ));

        // 数据库查询与结果转换
        return productTypeMapper.selectList(queryWrapper).stream()
                .map(list -> {
                    ProductTypeVo vo = new ProductTypeVo();
                    SqlTypeConverter.convertEntity(list, vo, "yyyy-mm-dd HH:mm:ss");
                    return vo;
                })
                .peek(vo -> log.info("转换后的商品类型: {}", JSON.toJSONString(vo)))
                .collect(Collectors.toList());
    }

    /**
     * @Author Wb
     * @Description 新增商品类型
     * @Date 9:29 2025/9/25
     * @Param [param]
     * @Return void
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveProductType(SaveProductTypeParam param) {
        try {
            ProductType productType = new ProductType();
            SqlTypeConverter.copyEntity(param, productType);
            productTypeMapper.insert(productType);
            log.info("新增商品类型成功！:{}", JSON.toJSONString(productType));
        } catch (Exception e) {
            log.error("新增商品类型失败", e);
             throw new BusinessException("新增商品类型失败", e);
        }
    }


    /**
     * @Author Wb
     * @Description 修改商品类型数据
     * @Date 11:25 2025/9/25
     * @Param [param]
     * @Return org.test.device.utils.ResultData
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateProductType(Integer id,SaveProductTypeParam param) {
        try {
            ProductType productType = productTypeMapper.selectById(id);
            SqlTypeConverter.copyEntity(param, productType);
            productTypeMapper.updateById(productType);
            log.info("修改商品类型成功！id:{},:{}", id, JSON.toJSONString(param));
        } catch (Exception e) {
            log.error("修改商品类型失败", e);
            throw new BusinessException("修改商品类型失败", e);
        }
    }


    /**
     * @Author Wb
     * @Description 删除产品类型 根据id
     * @Date 18:12 2025/9/26
     * @Param [id]
     * @Return void
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void deletedProductType(Integer id) {
        try {
            ProductType productType = productTypeMapper.selectById(id);
            productType.setDeleted(AttributesValue.DELETED.getCode());
            productTypeMapper.updateById(productType);
            log.info("删除商品类型成功！id:{}",id);
        } catch (Exception e) {
            log.error("删除商品类型失败！",e);
            throw new BusinessException("删除商品类型失败！",e);
        }
    }
}